import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Icon,
  Button,
  Table,
  Modal,
  Row,
  Col,
  Input,
  Select,
  Form,
  Upload,
  Radio,
  message,
} from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
const MyIcon = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1131883_m18hmgbwet.js', // 在 iconfont.cn 上生成
});
import styles from '../../../KnowledgeManagement/AntistopReply/index.less';
import axios from 'axios/index';
import { now } from 'moment';
import { getDownloadCorpus, postImportCorpus, knowledgeDialogNodeInfo } from '@/services/dialog';
import UserSession from '@/UserSession';

@connect(({ dialogCommon, loading }) => ({
  dialogCommon,
  loading: loading.models.data,
}))
class DialogSlotMark extends React.Component {
  getInit = async () => {
    const { nodeId, dialogId, stage } = this.state;
    const { dispatch } = this.props;

    if (UserSession.isSystemKnowledge()) {
			let res = await knowledgeDialogNodeInfo({
        dialogId: dialogId,
				nodeId: nodeId,
				nodeType: stage,
				field: "mark",
      });
      this.setState({
        mark: res.dialogStage.mark == null ? [] : res.dialogStage.mark,
        slots: res.dialogSlots,
        stageId: res.dialogStage.id,
      });
    } else {
      dispatch({
        type: "dialogCommon/getStage",
        payload: {
          dialogId: dialogId,
          nodeId: nodeId,
          stage: stage,
          field: "mark",
          urlPrefix: UserSession.isSystemKnowledge() ? 1 : null,
        },
        callback: (res) => {
          this.setState({
            mark: res.dialogStage.mark == null ? [] : res.dialogStage.mark,
            slots: res.dialogSlots,
            stageId: res.dialogStage.id,
          });
        },
      });
    }
  };

  componentDidMount() {
    this.getInit();
  }

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      visibleUpload: false,
      stageId: '',
      dialogId: props.dialogId,
      nodeId: props.nodeId,
      stage: props.stage,
      mark: [],
      word: {
        question: '',
        words: [],
        //markAs+filterRule字段内容筛选所用
        //markAs: "",
        //filterRule: "",
        //isConfirm字段信息确认所用
        isConfirm: true,
      },
      slots: [],
      markSlots: [],
      operaType: '',
      index: -1,
      currentPage: 1,
      pageSize: 10,
      fileList: [],
      uploading: false,
      editId: '',
    };
  }

  handleDeletes = item => {
    let { word } = this.state;
    const words = word.words;
    for (let i = 0; i < words.length; i++) {
      if (words[i] === item) {
        words.splice(i, 1);
        break;
      }
    }
    word['words'] = words;
    this.setState({
      word: word,
    });
  };

  editMark = (item, index) => {
    const { dispatch } = this.props;
    this.setState({ editId: item.id });
    dispatch({
      type: 'dialogCommon/splitWord',
      payload: {
        question: item.question,
      },
      callback: res => {
        this.setState({
          markSlots: res,
          word: item,
          visible: true,
          operaType: 'edit',
          index: index,
        });
      },
    });
  };

  wordsWordChange = (e, item) => {
    let { word } = this.state;
    const words = word.words;
    for (let i = 0; i < words.length; i++) {
      if (words[i] === item) {
        words[i]['word'] = e.target.value;
        break;
      }
    }
    word['words'] = words;
    this.setState({
      word: word,
    });
  };

  addWord = item => {
    let { word } = this.state;
    const words = word.words;
    words.push({ word: item, slotId: '' });
    word['words'] = words;
    this.setState({
      word: word,
    });
  };

  changeSlots = (val, index, valType) => {
    const { word } = this.state;

    switch (valType) {
      case 'slot':
        word.words[index].slotId = val;
        break;
      case 'markAs':
        word.words[index].markAs = val;
        break;
      case 'filterRule':
        word.words[index].filterRule = val;
        break;
    }

    this.setState({
      word: word,
    });
  };

  changeQuestion = event => {
    const { dispatch } = this.props;
    const { word } = this.state;
    word['question'] = event.target.value;
    this.setState({ word: word }, () => {
      if (this.state.word.question.trim() !== '') {
        dispatch({
          type: 'dialogCommon/splitWord',
          payload: {
            question: this.state.word.question,
          },
          callback: res => {
            this.setState({
              markSlots: res,
            });
          },
        });
      }
    });
  };

  save = saveType => {
    const { operaType, index, mark, word, stageId, stage, editId } = this.state;
    const { dispatch } = this.props;

    if (word.question == null || word.question == '' || word.question == undefined) {
      return message.error('语料回复话术不能为空！');
    }

    let obj = {};
    switch (this.state.stage) {
      case 'confirm':
        obj = {
          question: word.question,
          isConfirm: word.isConfirm,
        };
        break;
      default:
        obj = {
          question: word.question,
          words: word.words,
        };
        break;
    }
    if (operaType == 'add') {
      let nowMark = [];
      nowMark.push(obj);
      dispatch({
        type: 'dialogCommon/saveStage',
        payload: {
          id: stageId,
          field: 'mark',
          mark: nowMark,
          stage,
        },
        callback: res => {
          message.info(res.msg);
          // this.setState({editId:res})
          this.getInit();
        },
      });
    } else {
      mark[index] = obj;
      let nowMark = [];
      obj.id = editId;
      nowMark.push(obj);
      dispatch({
        type: 'dialogCommon/saveStage',
        payload: {
          id: stageId,
          field: 'mark',
          mark: nowMark,
          stage,
        },
        callback: res => {
          message.info(res.msg);
          this.getInit();
        },
      });
    }

    if (saveType === 'next') {
      this.setState({
        word: {
          question: '',
          words: [],
          isConfirm: true,
        },
        markSlots: [],
      });
    } else {
      this.setState({
        visible: false,
      });
    }
  };

  removeMark = (item, index) => {
    const { mark, stageId, currentPage, pageSize, editId, stage } = this.state;

    mark.splice((currentPage - 1) * pageSize + index, 1);
    this.setState({ editId: item.id });
    const { dispatch } = this.props;
    dispatch({
      type: 'dialogCommon/saveStage',
      payload: {
        id: stageId,
        field: 'mark',
        mark: mark,
        markId: item.id,
        stage,
      },
      callback: res => {
        message.info('删除成功');
        this.getInit();
        // if(currentPage > ((mark.length + pageSize - 1)/pageSize)){
        //   this.setState({
        //     currentPage: currentPage-1
        //   })
        // }
      },
    });
  };

  handleSubmitComment = val => {
    this.setState({
      currentPage: val,
    });
  };

  changePageSize = val => {
    this.setState({
      pageSize: val,
    });
  };

  handleCancelVisibleUpload = () => {
    this.setState({
      visibleUpload: false,
    });
  };

  uploadMark = () => {
    this.setState({
      visibleUpload: true,
    });
  };

  changeMarkRadio = event => {
    const { word } = this.state;
    word['isConfirm'] = event.target.value;
    this.setState({
      word,
    });
  };

  handleOk = e => {
    const { fileList, stage } = this.state;
    const formData = new FormData();
    fileList.forEach(file => {
      formData.append('file', file.originFileObj);
      formData.append('field', 'mark');
      formData.append('id', this.state.stageId);
      formData.append('stage', stage);
    });
    this.setState({
      uploading: true,
    });
    this.uploadFile(formData);
  };

  uploadFile = async data => {
    let res = await postImportCorpus(data);
    console.log(res);
    if (res.code == 0) {
      this.setState({ uploading: false }, () => {
        if (res.data.code) {
          return message.error(res.data.msg);
        } else {
          this.setState(
            {
              visibleUpload: false,
              fileList: [],
            },
            () => {
              message.success('导入成功');
              this.getInit();
            }
          );
        }
      });
    } else {
      message.error('导入失败请稍等再试');
    }
  };

  handleUpFile = info => {
    let fileList = [...info.fileList];
    fileList = fileList.slice(-1);
    fileList = fileList.map(file => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    if (fileList[0].size / 1024 / 1024 > 2) {
      // 2000000
      message.error('上传文件超出2M');
      this.setState({ fileList: [] });
    } else {
      this.setState({ fileList });
    }
  };

  downloadQaTemp = async () => {
    let res = await getDownloadCorpus();
  };

  render() {
    const columns = [
      {
        title: '语料',
        width: '40%',
        dataIndex: 'question',
      },
      {
        title: '标注状态',
        width: '40%',
        render: item => {
          return this.state.stage === 'confirm' ? (
            <div>{item.isConfirm ? '确认' : '不确认'}</div>
          ) : (
            <div>{item.words.length > 0 ? '已标注' : '未标注'}</div>
          );
        },
      },
      {
        title: '操作',
        width: '20%',
        render: (text, item, index) => {
          return (
            <div className={styles.pb}>
              <Button size='small' type='primary' disabled={UserSession.isSystemKnowledge()} onClick={() => this.editMark(item, index)}>
                <MyIcon style={{ marginRight: 5 }} type="icon-bi" />
                <FormattedMessage id="app.dialog.collect.mark" defaultMessage="Edit" />
              </Button>
              <Button
                disabled={UserSession.isSystemKnowledge()}
                onClick={() => this.removeMark(item, index)}
                style={{ marginLeft: 10}}
                type='danger'
                size='small'
              >
                <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" />
              </Button>
            </div>
          );
        },
      },
    ];

    //标注部分
    const columns2 = [
      {
        title: '取词',
        width: '40%',
        render: item => {
          return (
            <div>
              <Input
                placeholder="default size"
                value={item.word}
                onChange={event => {
                  this.wordsWordChange(event, item);
                }}
              />
            </div>
          );
        },
      },
      {
        title: '所属词槽',
        width: '40%',
        render: (text, item, index) => {
          return (
            <div>
              <Select
                value={item.slotId}
                style={{ width: '140px' }}
                onChange={value => this.changeSlots(value, index, 'slot')}
              >
                {this.state.slots.map(slot => (
                  <Select.Option value={slot.slotId} key={slot.slotId}>
                    {slot.slotName}
                  </Select.Option>
                ))}
              </Select>
            </div>
          );
        },
      },
      {
        title: '操作',
        width: '20%',
        render: item => {
          return (
            <div className={styles.pb}>
              <div
                style={{ background: '#e8313b' }}
                onClick={() => {
                  this.handleDeletes(item);
                }}
                className={styles.buttongl}
              >
                <span>
                  <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                </span>
                <span>
                  {' '}
                  <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" />
                </span>
              </div>
            </div>
          );
        },
      },
    ];

    //标注部分
    const columns3 = [
      {
        title: '取词',
        width: '25%',
        render: item => {
          return (
            <div style={{ width: '100px' }}>
              <Input
                placeholder="default size"
                value={item.word}
                onChange={event => {
                  this.wordsWordChange(event, item);
                }}
              />
            </div>
          );
        },
      },
      {
        title: '类型',
        width: '20%',
        render: (text, item, index) => {
          return (
            <div>
              <Select
                style={{ width: '80px' }}
                value={item.markAs}
                onChange={value => this.changeSlots(value, index, 'markAs')}
              >
                <Select.Option value="none">请选择</Select.Option>
                <Select.Option value="slot">词槽</Select.Option>
                <Select.Option value="filter">筛选规则</Select.Option>
              </Select>
            </div>
          );
        },
      },
      {
        title: '所属词槽',
        width: '20%',
        render: (text, item, index) => {
          return (
            <div>
              <Select
                value={item.slotId}
                style={{ width: '80px' }}
                onChange={value => this.changeSlots(value, index, 'slot')}
              >
                {this.state.slots.map(slot => (
                  <Select.Option value={slot.slotId} key={slot.slotId}>
                    {slot.slotName}
                  </Select.Option>
                ))}
              </Select>
            </div>
          );
        },
      },
      {
        title: '筛选规则',
        width: '20%',
        render: (text, item, index) => {
          return (
            <div>
              <Select
                style={{ width: '80px' }}
                value={item.filterRule}
                onChange={value => this.changeSlots(value, index, 'filterRule')}
                disabled={item.markAs === 'slot' ? true : false}
              >
                <Select.Option value="none">请选择</Select.Option>
                <Select.Option value="lt">小于</Select.Option>
                <Select.Option value="gt">大于</Select.Option>
                <Select.Option value="max">最大值</Select.Option>
                <Select.Option value="min">最小值</Select.Option>
                <Select.Option value="range">区间</Select.Option>
                <Select.Option value="not_contain">不包含</Select.Option>
                <Select.Option value="not_eq">不等于</Select.Option>
                <Select.Option value="eq">等于</Select.Option>
              </Select>
            </div>
          );
        },
      },
      {
        title: '操作',
        width: '15%',
        render: item => {
          return (
            <div className={styles.pb}>
              <div
                style={{ background: '#e8313b' }}
                onClick={() => {
                  this.handleDeletes(item);
                }}
                className={styles.buttongl}
              >
                <span>
                  <Icon size="small" type="delete" style={{ marginRight: 5 }} />
                </span>
                <span>
                  {' '}
                  <FormattedMessage id="app.dialog.question.delete" defaultMessage="out" />
                </span>
              </div>
            </div>
          );
        },
      },
    ];

    const formItemLayout = {
      labelCol: {
        xs: { span: 4 },
        sm: { span: 4 },
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 20 },
      },
    };

    const props = {
      // name: 'file',
      // headers: headData,
      // action: '/basic/lexicon/import',
      // accept: '.xlsx',
      // onChange: this.handleChangeByUpload,
      onRemove: file => {
        this.setState(state => {
          const index = state.fileList.indexOf(file);
          const newFileList = state.fileList.slice();
          newFileList.splice(index, 1);
          return {
            fileList: newFileList,
          };
        });
      },
      beforeUpload: file => {
        this.setState(state => ({
          fileList: [...state.fileList, file],
        }));
        return false;
      },
      accept: '.xlsx,.xls',
      onChange: this.handleUpFile,
    };

    return (
      <div>
        <div style={{ marginBottom: '20px' }}>
          <Button
            onClick={this.addMark}
            type="primary"
            icon="plus"
            style={{ padding: '0px 7px', marginRight: '10px' }}
            disabled={UserSession.isSystemKnowledge()}
          >
            添加语料
          </Button>
          <Button
            onClick={this.uploadMark}
            type="primary"
            icon="plus"
            disabled={UserSession.isSystemKnowledge()}
            ghost
          >
            导入语料
          </Button>
        </div>

        <div>
          <Table
            columns={columns}
            dataSource={this.state.mark} //数据
            pagination={{
              // 分页
              size: 'small',
              total: this.state.mark.length,
              current: this.state.currentPage, // 当前页
              showSizeChanger: true, // 是否显示可以设置几条一页的选项
              showQuickJumper: true,
              onChange: this.handleSubmitComment,
              onShowSizeChange: this.changePageSize,
            }}
          />
        </div>

        <Modal
          title={this.state.operaType === 'add' ? '添加语料' : '编辑语料'}
          visible={this.state.visible}
          onCancel={this.close}
          width={this.state.stage === 'filter' ? '600px' : '520px'}
          footer={
            this.state.operaType === 'add'
              ? [
                  <Button key={1} onClick={this.close}>
                    取消
                  </Button>,
                  <Button key={2} type="primary" onClick={() => this.save('next')}>
                    保存&下一个
                  </Button>,
                  <Button key={3} type="primary" onClick={() => this.save('this')}>
                    保存
                  </Button>,
                ]
              : [
                  <Button key={1} onClick={this.close}>
                    取消
                  </Button>,
                  <Button key={3} type="primary" onClick={() => this.save('this')}>
                    保存
                  </Button>,
                ]
          }
          getContainer={false}
        >
          <Row>
            <Col span={24}>
              <div style={{ marginBottom: '20px' }}>
                回复话术&nbsp;&nbsp;
                <Input
                  style={{ width: '85%', height: '30px' }}
                  placeholder=""
                  maxLength={100}
                  value={this.state.word.question}
                  onChange={event => {
                    this.changeQuestion(event);
                  }}
                />
              </div>

              {this.state.stage === 'confirm' ? (
                <div style={{ marginBottom: '20px', paddingLeft: '28px' }}>
                  标注&nbsp;&nbsp;
                  <Radio.Group
                    value={this.state.word.isConfirm}
                    onChange={event => {
                      this.changeMarkRadio(event);
                    }}
                  >
                    <Radio value={true}>确认</Radio>
                    <Radio value={false}>不确认</Radio>
                  </Radio.Group>
                </div>
              ) : (
                <div>
                  <div style={{ marginBottom: '20px' }}>
                    标注词槽&nbsp;&nbsp;
                    {this.state.markSlots.map((item, index) => (
                      <Button
                        key={index}
                        type="primary"
                        style={{ padding: '0 10px', marginRight: '10px' }}
                        onClick={() => this.addWord(item)}
                      >
                        {item}
                      </Button>
                    ))}
                  </div>

                  <div visible={false} style={{ marginBottom: '20px' }}>
                    <Table
                      columns={this.state.stage === 'filter' ? columns3 : columns2}
                      pagination={false}
                      dataSource={this.state.word.words} //数据
                    />
                  </div>
                </div>
              )}
            </Col>
          </Row>
        </Modal>

        <Modal
          title="导入标记语料"
          visible={this.state.visibleUpload}
          onCancel={this.handleCancelVisibleUpload}
          width="630px"
          centered
          footer={[
            <Button key="back" onClick={this.handleCancelVisibleUpload}>
              取消
            </Button>,
            <Button
              key="submit"
              type="primary"
              loading={this.state.loading}
              disabled={this.state.fileList.length === 0}
              onClick={this.handleOk}
            >
              {false ? '导入中' : '开始导入'}
            </Button>,
          ]}
          getContainer={false}
        >
          <Form {...formItemLayout}>
            <Form.Item label={<FormattedMessage id="app.overView.file" />}>
              <Upload {...props} fileList={this.state.fileList}>
                <Button>
                  <Icon type="upload" /> <FormattedMessage id="app.overView.file" />
                </Button>
              </Upload>
            </Form.Item>
            <Form.Item label={<FormattedMessage id="app.overView.file" />}>
              <div
                style={{
                  border: '1px solid grey',
                  padding: 10,
                  borderRadius: 10,
                  overflow: 'hidden',
                }}
              >
                <div>
                  •上传文件格式为.xls：
                  <span
                    style={{ color: 'blue', cursor: 'pointer' }}
                    onClick={() => this.downloadQaTemp()}
                  >
                    下载xls模板
                  </span>
                </div>
              </div>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    );
  }

  addMark = () => {
    this.setState({
      visible: true,
      word: {
        question: '',
        words: [],
        isConfirm: true,
      },
      markSlots: [],
      operaType: 'add',
    });
  };

  close = () => {
    this.setState({ visible: false });
  };
}

export default DialogSlotMark;
